import type { App } from 'vue'
import { AppRouteRecordRaw } from '@/types/route'
import type { RouteRecordRaw } from 'vue-router'

import { createRouter, createWebHistory } from 'vue-router'
import { constantRoutes } from './constantRoutes'
import { asyncRoutes } from './asyncRoutes'

// app router
// 创建一个可以被 Vue 应用程序使用的路由实例
export const router = createRouter({
  history: createWebHistory(),
  // 初始路由列表
  routes: constantRoutes as unknown as RouteRecordRaw[],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { left: 0, top: 0, behavior: 'smooth' }
    }
  }
})

// 根路由定向
export const homeRoute: AppRouteRecordRaw = {
  path: '/',
  name: 'homeRoute',
  redirect: '/customer/labour',
  meta: { hideMenu: true }
}

export const notFoundRoute: AppRouteRecordRaw = {
  path: '/:path(.*)*',
  name: 'notFoundRoute',
  redirect: '/',
  meta: {
    hideMenu: true
  }
}

// 将本地嵌套的路由，进行平铺，生成一个本地asyncRoutesMap
function parseMap(asyncRoutes: AppRouteRecordRaw[]) {
  const routesMap: any = {}
  function flat(routes: any) {
    return routes.reduce((pre: any, cur: AppRouteRecordRaw): any => {
      if (cur.name) {
        routesMap[cur.name] = cur
      }
      return pre.concat(Array.isArray(cur.children) ? flat(cur.children) : cur)
    }, [])
  }
  flat(asyncRoutes)
  return routesMap
}

export const routesMap = parseMap(asyncRoutes)

// 路由白名单
const resetWhiteNameList: string[] = []
const getRouteNames = (array: any[]) =>
  array.forEach((item) => {
    resetWhiteNameList.push(item.name)
    getRouteNames(item.children || [])
  })

getRouteNames(constantRoutes)

// 重置路由
export function resetRouter() {
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

// 配置路由器
export function setupRouter(app: App<Element>) {
  app.use(router)
}
